import { fetchEventSource } from '@microsoft/fetch-event-source'
import { ElMessage } from 'element-plus';
const api = import.meta.env.MODE == "development" ? import.meta.env.VITE_VUE_BASE_URL : globalParams.api;
export function fetchStream(data, signal, onMessage, onClose) {
    // fetchEventSource = fetch + EventSource结合 (单工通信sse要用到EventSource)
    let url = api + "/fusion/chat.do";
    const params = new URLSearchParams();
    params.append("type", data.type);
    params.append("requestMsg", data.requestMsg);
    return fetchEventSource(url, {
        method: "POST",
        headers: {
            // "Content-Type": "application/json",
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": 'text/event-stream',
        },
        // body: JSON.stringify(data),  // json格式
        body: params.toString(),  // 表单格式
        signal: signal,
        onmessage: onMessage,
        onclose: onClose,
        onopen: (response) => {
            if (response.ok) {
                return;
            } else {
                ElMessage.error('服务端异常')
                throw Promise.reject(new Error('服务端异常'))
            }
        }
    })
        
}